#!groovy

def call(name, imageName, needIngress) {
    def envMap = ['dev': 'dev环境k8s的APIServer地址', 'test': 'test环境k8s的APIServer地址']
    def apiServer = envMap[DEPLOY_ENV]

    assert name: 'name不能为空'
    assert imageName: 'imageName不能为空'

    stage('配置集群') {
        echo "配置${DEPLOY_ENV}集群"
        echo "${apiServer}"
        sh "kubectl config set-cluster k8s-${DEPLOY_ENV} --server=${apiServer} --insecure-skip-tls-verify=true"
        sh "kubectl config set-context ${DEPLOY_ENV} --cluster=k8s-${DEPLOY_ENV}"
        sh "kubectl config use-context ${DEPLOY_ENV}"
    }

    stage('部署集群') {
        echo "部署到集群，namespace为${DEPLOY_ENV}"
        sh "docker pull ${imageName}"
        sh """#!/bin/sh +x
if kubectl get deployment ${name} --namespace=${DEPLOY_ENV} >/dev/null 2>&1; then
  echo "Rolling-Update ${name}"
  kubectl set image deployment/${name} ${name}=${imageName} --namespace=${DEPLOY_ENV}
else
  echo "Create deployment ${name}"
  kubectl create -f ${K8S_CONF}/raw/${DEPLOY_ENV}/${name}-deployment.yml
fi

if kubectl get service ${name} --namespace=${DEPLOY_ENV} >/dev/null 2>&1; then
  echo "Service ${name} already exists."
else
  echo "Create service ${name}"
  kubectl create -f ${K8S_CONF}/raw/${DEPLOY_ENV}/${name}-service.yml
fi
"""
        if (needIngress == 'true') {
            sh """echo "${name} is a ui project"
if kubectl get ing ${name} --namespace=${DEPLOY_ENV} >/dev/null 2>&1; then
  echo "Ingress ${name} already exists."
else
  kubectl create -f ${K8S_CONF}/raw/${DEPLOY_ENV}/${name}-ingress.yml
fi
"""
        }
    }
}